package main

import (
	"cloud/entity"
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"io"
	"log"
	"net/http"
	"os"
	"sync"
)

var (
	db  *gorm.DB
	err error
)

func main() {
	/*db, err = gorm.Open(mysql.New(mysql.Config{
		DSN: "root:b92061055@tcp(localhost:3306)/gitee_repository?charset=utf8&parseTime=True",
	}))
	if err != nil {
		fmt.Printf("创建数据库连接失败:%v", err)
	}*/
	//CreateTable()
	FetchJson()
	//HandleJsonData()

}

func HandleJsonData() {
	fileName := "repo/repo56.json"
	file, err := os.Open(fileName)
	defer file.Close()
	if err != nil {
		fmt.Println(err)
	}
	dec := json.NewDecoder(file)
	repos := make([]*entity.Repository, 0)
	t, err := dec.Token()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%T: %v\n", t, t)
	for dec.More() {
		var repository entity.Repository
		if err = dec.Decode(&repository); err == io.EOF {
			break
		} else if err != nil {
			fmt.Println(err)
			continue
		}
		repos = append(repos, &repository)
	}
	t, err = dec.Token()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%T: %v\n", t, t)
	for _, repo := range repos {
		/*db.Create(repo.Namespace)
		repo.NamespaceId = repo.Namespace.NID
		db.Create(repo.Assigner)
		repo.AssignerId = repo.Assigner.AID
		db.Create(repo.Owner)
		repo.OwnerId = repo.Owner.OID
		db.Create(repo)
		fmt.Printf("%d save done\n", repo.RID)*/
		println(repo.ID)
	}
}

type ErrMsg struct {
	index int
	err   error
}

func FetchJson() {
	var (
		wg      = &sync.WaitGroup{}
		errChan = make(chan *ErrMsg)
	)
	for i := 101; i <= 125; i++ {
		wg.Add(1)
		go func(page int, wg *sync.WaitGroup, errChan chan *ErrMsg) {
			defer wg.Done()
			url := fmt.Sprintf("https://gitee.com/api/v5/search/repositories?q=go&page=%d&per_page=100", page)
			fileName := fmt.Sprintf("repo/GoRepo_Page%d.json", page)
			resp, err := http.Get(url)
			defer resp.Body.Close()
			if err != nil {
				errChan <- &ErrMsg{
					index: page,
					err:   err,
				}
				return
			}
			file, _ := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0644)
			_, err = io.Copy(file, resp.Body)
			if err != nil {
				errChan <- &ErrMsg{
					index: page,
					err:   err,
				}
				return
			}
			fmt.Printf("%d has done\n", page)

		}(i, wg, errChan)
		go func(errChan chan *ErrMsg) {
			for em := range errChan {
				fmt.Printf("%d %s", em.index, em.err)
			}
		}(errChan)
	}
	wg.Wait()
	close(errChan)
}

func CreateTable() {
	err := db.Migrator().CreateTable(&entity.Owner{})
	if err != nil {
		fmt.Println(err)
	}
	err = db.Migrator().CreateTable(&entity.Assigner{})
	if err != nil {
		fmt.Println(err)
	}
	err = db.Migrator().CreateTable(&entity.Namespace{})
	if err != nil {
		fmt.Println(err)
	}
	err = db.Migrator().CreateTable(&entity.Repository{})
	if err != nil {
		fmt.Println(err)
	}
}
